package parkingshare

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
)

//   系统配置文件对象
type Config struct {
	Mymap        map[string]string
	strcet       string
	Service      string
	MainPort     int
	RedisAddress string

	ClinetPort      int
	MainserviceAddr string
}

func (c *Config) InitConfig(path string) {
	c.Mymap = make(map[string]string)

	if len(path) == 0 {
		currentPath, err := getCurrentPath()
		if err != nil {
			return
		}
		path = currentPath + "main.conf"

	}
	f, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}

		s := strings.TrimSpace(string(b))
		fmt.Println(s)
		if strings.Index(s, "#") == 0 {
			continue
		}

		n1 := strings.Index(s, "[")
		n2 := strings.LastIndex(s, "]")
		if n1 > -1 && n2 > -1 && n2 > n1+1 {
			c.strcet = strings.TrimSpace(s[n1+1 : n2])
			continue
		}

		//		if len(c.strcet) == 0 {
		//			continue
		//		}
		index := strings.Index(s, "=")
		if index < 0 {
			continue
		}

		frist := strings.TrimSpace(s[:index])
		if len(frist) == 0 {
			continue
		}
		second := strings.TrimSpace(s[index+1:])

		pos := strings.Index(second, "\t#")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " #")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, "\t//")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " //")
		if pos > -1 {
			second = second[0:pos]
		}

		if len(second) == 0 {
			continue
		}

		key := strings.TrimSpace(frist)
		fmt.Println("key:" + key)
		fmt.Println("value:" + strings.TrimSpace(second))
		c.Mymap[key] = strings.TrimSpace(second)
	}

	t := c.Read("service")
	fmt.Println("t:" + t)
	c.Service = c.Read("service")
	fmt.Println("service" + c.Service)
	c.MainPort, err = strconv.Atoi(c.Read("mainPort"))
	if c.Service == "yes" && err != nil {
		fmt.Println("主控服务端口错误 ")
		return
	}

	c.RedisAddress = c.Read("redisAddress")
	c.ClinetPort, err = strconv.Atoi(c.Read("clinetPort"))

	if c.Service == "no" && err != nil {
		fmt.Println("客户服务端口错误 ")
		return
	}

	c.MainserviceAddr = c.Read("mainserviceAddr")

}

func (c *Config) Read(key string) string {
	fmt.Println("key：" + key)
	v, found := c.Mymap[key]
	if !found {
		return ""
	}
	fmt.Println("v：" + v)
	return v
}

func getCurrentPath() (string, error) {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return "", err
	}
	path, err := filepath.Abs(file)
	if err != nil {
		return "", err
	}
	i := strings.LastIndex(path, "/")
	if i < 0 {
		i = strings.LastIndex(path, "\\")
	}
	if i < 0 {
		return "", errors.New(`error: Can't find "/" or "\".`)
	}
	return string(path[0 : i+1]), nil
}
